package org.nViron.nvSim;

//~--- non-JDK imports --------------------------------------------------------

import java.util.HashMap;
import java.util.Iterator;

import org.nViron.nvRender.nvRenderer;

/**
 * Manager class that handles objects
 * @author Roland Haring <p>
 * <script type="text/javascript" src="http://www.ohloh.net/p/376434/widgets/project_basic_stats.js"></script>
 */
public abstract class nvObjectMgr implements nvVisual {
    public final static int INVALID_ID = 0;
    private static int      nextId;
    private final HashMap   objects = new HashMap();
    protected final nvSimulator   simulator;

    public nvObjectMgr(nvSimulator simulator) {
        this.simulator = simulator;
        nextId         = INVALID_ID;
    }

    protected int addObject(nvObject object) {
        synchronized (objects) {
            objects.put(object.getId(), object);
        }
        return object.getId();
    }

    protected int getNextId() throws IndexOutOfBoundsException {
        nextId++;

        if (nextId == INVALID_ID) {
            throw new IndexOutOfBoundsException("Object ID overrun!");
        }

        return nextId;
    }

    protected nvObject getObject(int id) {
        return (nvObject) objects.get(id);
    }

    protected HashMap getObjects() {
        return objects;
    }

    public nvSimulator getSimulator() {
        return simulator;
    }

    public void remove(int id) {
        nvObject object = getObject(id);
        remove(object);
    }

    public void remove(nvObject object) {
        synchronized (objects) {
            objects.remove(object.getId());
        }
    }

    public void render(nvRenderer renderer) {
        synchronized (objects) {
            for (Iterator i = objects.values().iterator(); i.hasNext(); ) {
                nvObject object = (nvObject)i.next();
                object.render(renderer);
            }
        }
    }

    public int size() {
        return objects.size();
    }

    public void update(float timeStep) {
        // update places
        synchronized (objects) {
            for (Iterator i = objects.values().iterator(); i.hasNext(); ) {
                nvObject object = (nvObject)i.next();
                object.update(timeStep);
            }
        }
    }
}



